var express = require('express');
const router = express.Router();
var fs = require("fs");
var multer  = require('multer');
var storage = multer.diskStorage({
   destination: function (req, file, cb) {
       cb(null, __dirname);
   }
}); 

router.post('/', multer({storage: storage}).single('Capsule'), async(req, res, next) => {
   console.log(req.file);  // 上传的文件信息
   var promise=new Promise(function(resolve,reject){
      var des_file = __dirname + "/capsule/" + req.file.originalname;
      fs.readFile(req.file.path, function(err, data){
         if(err){
            console.log(err);
            resolve(response={
               message:'Error', 
               filename:req.file.originalname,
               status:400,
               error:err});
         }else{
            fs.writeFile(des_file, data, function (err){
               if(err){
                  console.log(err);
                  resolve(response={
                        message:'Error', 
                        filename:req.file.originalname,
                        status:400,
                        error:err});
               }else{
                     resolve(response = {
                        message:'File uploaded successfully', 
                        filename:req.file.originalname,
                        status:200});
               } 
            });
         }
      });
   });
   promise.then((value)=>{
      fs.unlink(req.file.path, function(err){
      if(err){
         console.log(err);
      }
      res.end(JSON.stringify(value));
      });
   });    
})

module.exports=router;